<template>
  <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
    <a-form @submit="submit" :form="form">
      <a-form-item
        :label="$t('deviceName')"
        :labelCol="{ span: 7 }"
        :wrapperCol="{ span: 10 }"
      >
        <a-input
          v-decorator="[
            'deviceName',
            { rules: [{ required: true, message: '设备名称不得为空' }] },
          ]"
          :placeholder="$t('deviceNameInput')"
        />
      </a-form-item>
      <a-form-item
        :label="$t('ipAddr')"
        :labelCol="{ span: 7 }"
        :wrapperCol="{ span: 10 }"
      >
        <a-input
          v-decorator="[
            'ipAddr',
            { rules: [{ required: true, message: 'IP地址不得为空' }] },
          ]"
          :placeholder="$t('ipAddrInput')"
        />
      </a-form-item>
      <a-form-item
        :label="$t('productId')"
        :labelCol="{ span: 7 }"
        :wrapperCol="{ span: 10 }"
      >
        <a-select
          v-decorator="[
            'productId',
            { rules: [{ required: true, message: '必须选择一个所属产品' }] },
          ]"
        >
          <a-select-option
            v-for="item in productList"
            :value="item.id"
            :key="item.id"
            >{{ item.productName }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item
        style="margin-top: 24px"
        :wrapperCol="{ span: 10, offset: 7 }"
      >
        <a-button type="primary" @click="submit">{{ $t("submit") }}</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import { productPage } from "@/services/product";
import { saveOrUpdateDevice, deviceDetail } from "@/services/device";

export default {
  name: "BasicForm",
  i18n: require("./i18n"),
  data() {
    return {
      form: this.$form.createForm(this),
      value: 1,
      productList: [],
    };
  },
  mounted() {
    this.initDevice();
    this.queryProductPage();
  },
  methods: {
    initDevice() {
      deviceDetail(this.$route.params.id).then((rep) => {
        const data = rep.data.data;
        this.form.setFieldsValue({
          deviceName: data.deviceName,
          ipAddr: data.ipAddr,
          productId: data.product.id,
        });
      });
    },
    submit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.id = this.$route.params.id;
          saveOrUpdateDevice(values).then((rep) => {
            if (rep.data.success) {
              this.$message.success("更新设备成功");
            } else {
              this.$message.error(rep.data.msg);
            }
          });
        }
      });
    },
    queryProductPage() {
      productPage({ entity: { status: 1 } }).then((rep) => {
        this.productList = rep.data.data.records;
      });
    },
  },
  computed: {
    desc() {
      return this.$t("pageDesc");
    },
  },
};
</script>

<style scoped>
</style>
